//
//  RCSScanQRCodeViewController.m
//  RCS
//
//  Created by on 15-1-21.
//  Copyright (c) 2015年. All rights reserved.

#import "ASScanQRCodeVC.h"
#import "ZXingObjC.h"

typedef void (^RCSCameraAuthorizationHandler) (BOOL authorized);

@interface ASScanQRCodeViewController () <AVCaptureMetadataOutputObjectsDelegate, ZXCaptureDelegate>

@property (nonatomic, strong) ZXCapture   *capture;          // ZXing摄像
@property (nonatomic, assign) BOOL        isCapturing;       // 摄像标记，YES正在扫描，否则NO，默认NO
@property (nonatomic, assign) BOOL        isViewLoaded;      // 页面是否加载完成，YES加载成功，否则NO，默认NO

@property (nonatomic, strong) UIImageView *scanLineUpAndDown;//上下滚动的扫描标记
@property (nonatomic, strong) UIImageView *scanBoxView;      //放二维码的框
@property (nonatomic, strong) UILabel     *operTip;              //提示
@property (nonatomic, strong) UIImageView *maskBKView;       //二维码半透明蒙板

//用来扫描二维码的相关类
@property (nonatomic, strong) AVCaptureDevice            *device;
@property (nonatomic, strong) AVCaptureDeviceInput       *input;
@property (nonatomic, strong) AVCaptureMetadataOutput    *output;
@property (nonatomic, strong) AVCaptureSession           *session;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *preview;
@property (nonatomic, assign) BOOL                       isReading;
@property (nonatomic, strong) UIView                     *loadingView; //正在加载View
@property (nonatomic, strong) UILabel                    *loadingLabel; //正在加载Label
@property (nonatomic, assign) BOOL                       isloadingFlag; //是否第一次加载

@end



@implementation ASScanQRCodeViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self configureBackgroudAndNaviInfo];
    [self checkCameraAuth];
    
    if (SYSTEM_VERSION < 7.0)
    {
        ;
    }
    else
    {
        //添加扫描子控件
        [self createCameraOverlayView];
        [self setOverView];
        
        //加载中...
        CGPoint center = self.view.center;
        self.loadingView = [[UIView alloc] initWithFrame:_maskBKView.frame];
        self.loadingView.backgroundColor = [UIColor blackColor];
        self.loadingLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
        CGPoint labelCenter = self.loadingLabel.center;
        labelCenter.x = center.x;
        labelCenter.y = self.view.frame.size.height /2;
        self.loadingLabel.center = labelCenter;
        self.loadingLabel.text = @"正在加载...";
        [self.loadingLabel setFont:[UIFont systemFontOfSize:16.0f]];
        self.loadingLabel.textAlignment = NSTextAlignmentCenter;
        self.loadingLabel.textColor = [UIColor colorWithRed:134/255.0 green:139/255.0 blue:142/255.0 alpha:1];
        [self.loadingView addSubview:self.loadingLabel];
        [self.view addSubview:self.loadingView];
        self.isloadingFlag = YES;
    
        _session = nil;
        [self startReading];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (SYSTEM_VERSION < 7.0)
    {
        //创建二维码捕捉
        [self createBarcodeCapture];
         self.capture.delegate = self;
        //添加扫描子控件
        [self createCameraOverlayView];
    }
    else
    {
        if(self.isloadingFlag)
        {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.loadingView.hidden = YES;
                self.loadingLabel.hidden = YES;
                self.isloadingFlag = NO;
                [self.view.layer insertSublayer:self.preview atIndex:0];
                _isReading = YES;
                [_session startRunning];

            });
        }
        else
        {
            [self.view.layer insertSublayer:self.preview atIndex:0];
            _isReading = YES;
            [_session startRunning];
        }
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.isViewLoaded = YES;
    self.isCapturing = YES;
}

- (void)dealloc
{
    self.isCapturing = NO;
    self.isViewLoaded = NO;
    [self.capture stop];
    self.capture.delegate = nil;
    self.capture = nil;
}

#pragma mark - 业务逻辑

/**
 *  对于扫描结果的操作
 */
- (void)actionForScanResult:(NSString *)strQRCodeValue
{
    if ([strQRCodeValue canBeConvertedToEncoding:NSUTF8StringEncoding])//中文编码
    {
        //[self pushNewViewControllerBy:[strQRCodeValue stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    else if ([strQRCodeValue canBeConvertedToEncoding:NSShiftJISStringEncoding])
    {
        NSString *stringValue = [NSString stringWithCString:[strQRCodeValue cStringUsingEncoding:NSShiftJISStringEncoding]
                                                   encoding:NSUTF8StringEncoding];//转换日体编码
        //[self pushNewViewControllerBy:stringValue];
    }
    else
    {
        //[self pushNewViewControllerBy:strQRCodeValue];
    }
}


#pragma mark - ZBar扫描相关

/**
 *  创建二维码捕捉
 */
- (void)createBarcodeCapture
{
#if TARGET_IPHONE_SIMULATOR
#else
    if (self.capture == nil)
    {
        self.capture = [[ZXCapture alloc] init];
        self.capture.camera = self.capture.back;
        self.capture.focusMode = AVCaptureFocusModeContinuousAutoFocus;
        self.capture.rotation = 90.0f;
        self.capture.layer.frame = self.view.bounds;
        [self.view.layer addSublayer:self.capture.layer];
    }
#endif
}

#pragma mark -- ZXCaptureDelegate Method
- (void)captureResult:(ZXCapture *)capture result:(ZXResult *)result
{
    if (!result)//扫描失败
    {
        return;
    }
    
    NSString *formatString = [self barcodeFormatToString:result.barcodeFormat];
    if (![formatString isEqualToString:@"QR Code"])
    {
        return;
    }
    
    if (self.isCapturing == NO)
    {
        return;
    }
    
    self.isCapturing = NO;
    
    if (self.isViewLoaded == NO)
    {
        return;
    }
    
    [self actionForScanResult:result.text];
}

- (NSString *)barcodeFormatToString:(ZXBarcodeFormat)format
{
    switch (format)
    {
        case kBarcodeFormatAztec:
            return @"Aztec";
            
        case kBarcodeFormatCodabar:
            return @"CODABAR";
            
        case kBarcodeFormatCode39:
            return @"Code 39";
            
        case kBarcodeFormatCode93:
            return @"Code 93";
            
        case kBarcodeFormatCode128:
            return @"Code 128";
            
        case kBarcodeFormatDataMatrix:
            return @"Data Matrix";
            
        case kBarcodeFormatEan8:
            return @"EAN-8";
            
        case kBarcodeFormatEan13:
            return @"EAN-13";
            
        case kBarcodeFormatITF:
            return @"ITF";
            
        case kBarcodeFormatPDF417:
            return @"PDF417";
            
        case kBarcodeFormatQRCode:
            return @"QR Code";
            
        case kBarcodeFormatRSS14:
            return @"RSS 14";
            
        case kBarcodeFormatRSSExpanded:
            return @"RSS Expanded";
            
        case kBarcodeFormatUPCA:
            return @"UPCA";
            
        case kBarcodeFormatUPCE:
            return @"UPCE";
            
        case kBarcodeFormatUPCEANExtension:
            return @"UPC/EAN extension";
            
        default:
            return @"Unknown";
    }
}

# pragma mark - 系统扫描相关
- (BOOL)startReading
{
    NSError *error;
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    if (!input)
    {
        return NO;
    }
    
    _session = [[AVCaptureSession alloc] init];
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    [_session addInput:input];
    
    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    [_session addOutput:captureMetadataOutput];
    
    //dispatch_queue_t dispatchQueue;
    //dispatchQueue = dispatch_queue_create("myQueue", NULL);
    //[captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    [captureMetadataOutput setMetadataObjectTypes:[NSArray arrayWithObject:AVMetadataObjectTypeQRCode]];
    
    CGSize size = self.view.bounds.size;
    CGRect cropRect = CGRectMake(40, 120, [UIScreen mainScreen].applicationFrame.size.width - 80, [UIScreen mainScreen].applicationFrame.size.width - 80);
    captureMetadataOutput.rectOfInterest = CGRectMake(cropRect.origin.y/size.height,
                                                      cropRect.origin.x/size.width,
                                                      cropRect.size.height/size.height,
                                                      cropRect.size.width/size.width);
    
    _preview = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_session];
    [_preview setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    [_preview setFrame:self.view.layer.bounds];
    
    return YES;
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputMetadataObjects:(NSArray *)metadataObjects
          fromConnection:(AVCaptureConnection *)connection
{
    if (!_isReading)
    {
        [self stopReading];
        return;
    }
    
    NSString *stringValue;
    
    if (metadataObjects != nil && [metadataObjects count] > 0)
    {
        _isReading = NO;
        
        AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
        
        // AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObj.stringValue;
        
        [self invokeInterface:stringValue];
    }
    else
    {
        return;
    }
}

- (void)invokeInterface:(NSString *)url
{
    // 判断是否是扫实习单位产生的二维码
    // http://211.65.216.54//checkXiaowaiIn.action?caseTypeId=1&time=1491497000447&accountId=22
    if ([url rangeOfString:@"checkXiaowaiIn.action?caseTypeId"].length > 0)
    {
        NSString *userCode = [ASAppDelegate sharedAppDelegate].userInfo.userId;
        NSString *totalUrl = [NSString stringWithFormat:@"%@&fkUserId=%@", url, userCode];
        [SVProgressHUD showWithStatus:@"签到中..." maskType:SVProgressHUDMaskTypeClear];
        ASNetworkEngine *networkingEngine = [ASNetworkEngine sharedInstance];
        
        [networkingEngine POST:totalUrl parameters:nil success:^(id responseObject) {
            NSDictionary* jsonRsp = (NSDictionary *)responseObject;
            if (isSuccessRsp(jsonRsp))
            {
                [SVProgressHUD showSuccessWithStatus:@"签到成功"];
                if (_delegate && [_delegate respondsToSelector:@selector(scanOk)])
                {
                    [_delegate scanOk];
                }
            }
            else
            {
                [SVProgressHUD showErrorWithStatus:errorMsgRsp(jsonRsp)];
            }
        } failure:^(NSError *error) {
            
            [SVProgressHUD showErrorWithStatus:@"网络异常，请稍后再试"];
        }];

        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    
    // 此处得到二维码解析出来的值立即处理
    // http://211.65.216.54//checkIn.action?fkActionId=QQW&time=1460952439970
    NSString *userCode = [ASAppDelegate sharedAppDelegate].userInfo.userCode;
    NSString *totalUrl = [NSString stringWithFormat:@"%@&userCode=%@", url, userCode];
    
    [SVProgressHUD showWithStatus:@"签到中..." maskType:SVProgressHUDMaskTypeClear];
    ASNetworkEngine *networkingEngine = [ASNetworkEngine sharedInstance];
    
    [networkingEngine POST:totalUrl parameters:nil success:^(id responseObject) {
        NSDictionary* jsonRsp = (NSDictionary *)responseObject;
        if (isSuccessRsp(jsonRsp))
        {
            //NSString* str = [jsonRsp objectForKey:kASJsonMsgData];
            [SVProgressHUD showSuccessWithStatus:@"签到成功"];
            if (_delegate && [_delegate respondsToSelector:@selector(scanOk)]) {
                [_delegate scanOk];
            }
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:errorMsgRsp(jsonRsp)];
        }
    } failure:^(NSError *error) {
        //[SVProgressHUD showErrorWithStatus:error.description];
        [SVProgressHUD showErrorWithStatus:@"网络异常，请稍后再试"];
    }];
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)stopReading
{
    [_session stopRunning];
    [_preview removeFromSuperlayer];
}

/**
 *  配置导航和背景
 */
- (void)configureBackgroudAndNaviInfo
{
    //导航
    self.strNavTitle = @"扫一扫";
    [self setLeftButtonWithImageName:@"ic_back" bgImageName:nil];
    
    //二维码半透明蒙板
    self.view.backgroundColor = [UIColor blackColor];
    if (SYSTEM_VERSION < 7.0)
    {
        _maskBKView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"contact_code_bg"]];
    }
    else
    {
        _maskBKView = [[UIImageView alloc] init];
    }
    _maskBKView.frame = CGRectMake(0, -40, self.view.frame.size.width, self.view.frame.size.height);
    
    if (iPhone4)
    {
        _maskBKView.frame = CGRectMake(0, -84, self.view.frame.size.width, self.view.frame.size.height+88);
    }
    
    //适配iOS6
    if (SYSTEM_VERSION < 7.0)
    {
        _maskBKView.frame = CGRectMake(0, -74, self.view.frame.size.width, self.view.frame.size.height+108);
    }
    [self.view addSubview:_maskBKView];
}

/**
 *  添加扫描子控件
 */
- (void)createCameraOverlayView
{
#if TARGET_IPHONE_SIMULATOR
    
#else
    //放二维码的框
    CGPoint center = self.view.center;
    if (_scanBoxView == nil)
    {
        _scanBoxView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 243, 243)];
        _scanBoxView.image = [UIImage imageNamed:@"contact_me_two dimension_sweep_box"];
        _scanBoxView.center = center;
        _scanBoxView.center = CGPointMake(_scanBoxView.center.x, _scanBoxView.center.y - 64);
        [self.view addSubview:_scanBoxView];
    }
    
    //提示语
    if (_operTip == nil)
    {
        _operTip = [[UILabel alloc] initWithFrame:CGRectMake(0, _scanBoxView.frame.origin.y + 263, self.view.frame.size.width, 30)];
        CGPoint operTipCenter = _operTip.center;
        operTipCenter.x = center.x;
        _operTip.center = operTipCenter;
        _operTip.text = @"将二维码放在扫描框内，即可自动扫描!";
        _operTip.backgroundColor = [UIColor clearColor];
        [_operTip setFont:[UIFont systemFontOfSize:15.0f]];
        _operTip.textAlignment = NSTextAlignmentCenter;
        _operTip.textColor = [UIColor whiteColor];
        [self.view addSubview:_operTip];
    }
    
    //扫描滚动标记
    if (_scanLineUpAndDown == nil)
    {
        _scanLineUpAndDown = [[UIImageView alloc] initWithFrame:CGRectMake(0,0, 243, 20)];
        _scanLineUpAndDown.image = [UIImage imageNamed:@"contact_me_two dimension_sweep"];
        [_scanBoxView addSubview:_scanLineUpAndDown];
        [_scanLineUpAndDown.layer addAnimation:[self fromH:0 toH:(225) ] forKey:@"position"];
    }
#endif
}


#pragma mark - 添加模糊效果
- (void)setOverView
{
    CGFloat width = CGRectGetWidth(self.view.frame);
    CGFloat height = CGRectGetHeight(self.view.frame);
    
    CGFloat x = CGRectGetMinX(_scanBoxView.frame);
    CGFloat y = CGRectGetMinY(_scanBoxView.frame);
    CGFloat w = CGRectGetWidth(_scanBoxView.frame);
    CGFloat h = CGRectGetHeight(_scanBoxView.frame);
    
    [self creatView:CGRectMake(0, 0, width, y)];
    [self creatView:CGRectMake(0, y, x, h)];
    [self creatView:CGRectMake(0, y + h, width, height - y - h)];
    [self creatView:CGRectMake(x + w, y, width - x - w, h)];
}

- (void)creatView:(CGRect)rect
{
    CGFloat alpha = 0.5;
    UIColor *backColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7];
    UIView *view = [[UIView alloc] initWithFrame:rect];
    view.backgroundColor = backColor;
    view.alpha = alpha;
    [self.view addSubview:view];
}

/**
 *  检查相机权限
 */
- (void)checkCameraAuth
{
    [self hasCameraAuthorization:^(BOOL authorized){
        if (authorized)
        {
            
        }
        else
        {
            // 提示用户没有权限
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"请在iPhone的“设置-隐私-相机”选项中，允许和飞信访问你的相机。"
                                                           delegate:self
                                                  cancelButtonTitle:nil
                                                  otherButtonTitles:@"确定", nil];
            [alert show];
        }
    }];
}


/**
 *  配置动画
 */
- (CABasicAnimation *)fromH:(float)height toH:(float)height1 //纵向移动
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"];
    animation.fromValue = [NSNumber numberWithFloat:height]; // 起始点
    animation.toValue = [NSNumber numberWithFloat:height1]; // 终了点
    animation.duration = 1.5f;
    animation.fillMode = kCAFillModeBoth;
    animation.repeatCount = FLT_MAX;
    animation.removedOnCompletion = NO;
    animation.autoreverses = YES;
    return animation;
}

- (void)animation1
{
    [UIView animateWithDuration:1.0 animations:^{
        _scanLineUpAndDown.frame = CGRectMake(40, _scanBoxView.frame.origin.y + 223, 243, 20);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:1.0 animations:^{
            _scanLineUpAndDown.frame = CGRectMake(40, _scanBoxView.frame.origin.y - 3, 243, 20);
        }];
    }];
}

//判断是否扫描公众的url
- (BOOL)isPublicScan:(NSString*)qrResult findstr:(NSString*)findScanstr
{
    if ((nil == qrResult) || (nil == findScanstr) || (0 == qrResult.length) || (0 == findScanstr.length))
    {
        return NO;
    }
    
    NSRange range = [qrResult rangeOfString:findScanstr];
    if (range.location != NSNotFound) {
        return YES;
    }
    
    return NO;
}

/**
 *	@brief	检查是否得到摄像头使用授权
 *
 *	@param 	handler 	检查结果block回调
 */
- (void)hasCameraAuthorization:(RCSCameraAuthorizationHandler)handler{
    
    if (SYSTEM_VERSION < 7.0)
    {
        handler(YES);
        return;
    }
    
    //判断是否在访问限制（家长控制）下关闭了相机 或 设备没有摄像头
    if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        handler(NO);
        return;
    }
    
    //判断是否在隐私中关闭了相机
    NSString *mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if (authStatus == AVAuthorizationStatusAuthorized || authStatus == AVAuthorizationStatusNotDetermined)
    {
        handler(YES);
        return;
    }
    else
    {
        handler(NO);
        return;
    }
    
    
    //    if (SYSTEM_VERSION < 7.0) {
    //        handler(YES);
    //        return;
    //    }
    //
    //    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    //
    //    //用户已经授权
    //    if (AVAuthorizationStatusAuthorized == status) {
    //        handler(YES);
    //        return;
    //    }
    //    handler(NO);
    
    
    //    //如果应用第一次访问相机尚未选择权限、选择后block回调
    //    if (AVAuthorizationStatusNotDetermined == status && (status != AVAuthorizationStatusRestricted || status != AVAuthorizationStatusDenied)) {
    //        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted){
    //            dispatch_async(dispatch_get_main_queue(), ^{
    //                handler(granted);
    //            });
    //        }];
    //    }else{
    //        handler(NO);
    //    }
}


@end
